package com.chen10.gobang.config.interceptor;

import com.chen10.gobang.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
@Slf4j
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 如果是HttpUrlConnection，则可以从中提取查询参数

        if (request instanceof org.springframework.http.server.ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (org.springframework.http.server.ServletServerHttpRequest) request;
            String token = servletRequest.getServletRequest().getParameter("token");
            log.info("ws:  token: {}", token);
            if (token != null && !token.isEmpty()) {
                // 验证token是否有效且未过期
                if (JwtUtil.verifyToken(token) && !JwtUtil.isTokenExpired(token)) {
                    attributes.put("token", token);
                    return true; // 继续握手过程
                } else {
                    log.warn("用户尝试使用已过期的token建立连接: {}", token);
                    response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED); // 设置响应状态码为401
                    return false; // 拒绝握手
                }
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        // 握手完成后的逻辑（如果有）
    }
}
